const path = require('path');
const fs = require('fs');
const db = require('./backend/db');

// 读取节假日数据
const holidaysData = JSON.parse(fs.readFileSync(path.resolve(__dirname, '2025_holidays.json'), 'utf8'));

// 导入节假日数据到数据库
function importHolidays() {
  console.log('开始导入2025年节假日数据...');

  // 先清空holidays表
  db.run('DELETE FROM holidays', (err) => {
    if (err) {
      console.error('清空holidays表失败:', err.message);
      return;
    }

    let totalInserted = 0;
    const holidays = holidaysData.holidays;

    // 处理每个节假日
    holidays.forEach(holiday => {
      // 处理单个日期的节假日
      if (holiday.date) {
        insertHoliday(holiday.name, holiday.date, 1, holiday.type, () => {
          totalInserted++;
          checkIfAllInserted();
        });
      }
      // 处理日期范围的节假日
      else if (holiday.date_range && holiday.date_range.length === 2) {
        const startDate = new Date(holiday.date_range[0]);
        const endDate = new Date(holiday.date_range[1]);

        let currentDate = new Date(startDate);
        while (currentDate <= endDate) {
          const dateStr = currentDate.toISOString().split('T')[0];
          insertHoliday(holiday.name, dateStr, 1, holiday.type, () => {
            totalInserted++;
            checkIfAllInserted();
          });

          // 移动到下一天
          currentDate.setDate(currentDate.getDate() + 1);
        }
      }

      // 处理调休工作日
      if (holiday.adjust_work_days && holiday.adjust_work_days.length > 0) {
        holiday.adjust_work_days.forEach(workDay => {
          insertHoliday(`${holiday.name}调休`, workDay, 2, '调休工作日', () => {
            totalInserted++;
            checkIfAllInserted();
          });
        });
      }
    });

    // 检查是否所有数据都已插入
    function checkIfAllInserted() {
      // 计算应该插入的总记录数
      let expectedTotal = 0;
      holidays.forEach(holiday => {
        // 计算节假日天数
        if (holiday.date) {
          expectedTotal++;
        } else if (holiday.date_range) {
          const startDate = new Date(holiday.date_range[0]);
          const endDate = new Date(holiday.date_range[1]);
          const days = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
          expectedTotal += days;
        }

        // 计算调休工作日天数
        if (holiday.adjust_work_days) {
          expectedTotal += holiday.adjust_work_days.length;
        }
      });

      if (totalInserted === expectedTotal) {
        console.log(`成功导入${totalInserted}条节假日数据`);
        db.close();
      }
    }
  });
}

// 插入单个节假日记录
function insertHoliday(name, date, type, description, callback) {
  const year = date.split('-')[0];

  db.run(
    'INSERT INTO holidays (name, date, type, year, description) VALUES (?, ?, ?, ?, ?)',
    [name, date, type, year, description],
    (err) => {
      if (err) {
        console.error(`插入${date}数据失败:`, err.message);
      } else {
        // console.log(`成功插入: ${name} - ${date}`);
      }
      callback();
    }
  );
}

// 执行导入
importHolidays();